//从前序与中序遍历序列构造二叉树
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder,
                        int& prei, int inbegin, int inend)
    {
        //左右区间不存在，则不需要创建节点
        if(inbegin > inend)
            return nullptr;
        
        TreeNode* root = new TreeNode(preorder[prei]);
        int rooti = inbegin;//用于划分左右子树
        while(preorder[prei] != inorder[rooti])
        {
            ++rooti;
        }
        ++prei;
        root->left = _buildTree(preorder, inorder, prei, inbegin, rooti - 1);
        root->right = _buildTree(preorder, inorder, prei, rooti + 1, inend);
        return root;

    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) 
    {
        //利用前序确定根，中序确定左右子树
        int prei = 0;//用于遍历前序向量
        TreeNode* root = _buildTree(preorder, inorder, prei, 0, inorder.size() - 1);
        return root;
    }
};

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) 
    {
        //思路
        //将问题划分成 1、遍历左路节点
        //           2、遍历左路节点的右子树

        vector<int> ret;
        stack<TreeNode*> st;
        TreeNode* cur = nullptr;
        if(root)
            cur = root;
        
        while(cur || !st.empty())
        {
            while(cur)//遍历左路节点
            {
                ret.push_back(cur->val);
                st.push(cur);
                cur = cur->left;
            }
            //遍历左路节点的右子树
            TreeNode* top = st.top();
            st.pop();

            cur = top->right;//子问题的方式访问右子树
        }
        return ret;
    }
};